/*
 * @Author: yangzonglong
 * @Date: 2021-03-10 15:38:29
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-07-20 14:52:31
 * @Auditor:
 */
import React, { useMemo, useImperativeHandle, forwardRef, useState, } from 'react';
import { FormItemProps } from 'antd/lib/form';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import Template from 'art-template'

export interface TemplateProps extends CanvasItemProps {
  initialValue?: string;
  isDesign?: boolean;
  formItemProps?: FormItemProps;
  templateProps?: {
    scriptText?: string
  };
}

interface RefProps {
  setData(data: any): void;
}

const data = { list: [] }

const style = { width: '100%', 'min-height': '40px' }

const template = '<div></div>'

const App = (props: TemplateProps, ref: React.Ref<RefProps>) => {


  const { domComplete, formItemProps, templateProps, initialValue: value, isDesign, ...canvasProps } = props;

  const [initialValue, setInitialValue] = useState(data)

  useQueryControlWrap(canvasProps.id, '', domComplete);

  const html = useMemo(() => {
    const renderResult = Template.compile(templateProps?.scriptText || template)
    return renderResult(initialValue ? (Array.isArray(initialValue) ? { list: initialValue } : initialValue) : data)
  }, [initialValue, templateProps])

  useImperativeHandle(ref, () => ({
    setData(data: any) {
      setInitialValue(data)
    },
  }));

  return (
    <div {...canvasProps} {...formItemProps} style={style} >
      {formItemProps?.label}
      {
        isDesign ? <div style={{ color: 'rgba(0, 121, 255, 0.8)' }}>{templateProps?.scriptText || template}</div> : <div dangerouslySetInnerHTML={{ __html: html }} />
      }
    </div>
  );
};

export default forwardRef(App);
